﻿using CanDichVu.FrameWork.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace CanDichVu.FrameWork.Conrtron
{
    public class ContronllerBase : Controller
    {
        private readonly CanDichVu.FrameWork.Helper.HtmlHelper _ihtml = new CanDichVu.FrameWork.Helper.HtmlHelper();
        private UTContextKey utContext = null;
        public UTContextKey UtContext
        {
            get
            {
                if (utContext == null)
                {
                    utContext = Session[UTContextKey.SessionContextKey] as UTContextKey;
                    if (utContext == null)
                    {
                        utContext = new UTContextKey();
                        Session[UTContextKey.SessionContextKey] = utContext;
                    }
                }
                return utContext;
            }
            private set { utContext = value; }
        }



        public JsonResult JsonError(string message)
        {
            JsonResualt response = new JsonResualt() { Status = JsonResualt.OperationFailure, Message = message };
            return new JsonResult() { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        public JsonResult JsonSuccess(string redirectUrl, string message = null)
        {
            JsonResualt response = new JsonResualt();
            response.Status = JsonResualt.OperationSuccess;
            response.RedirectUrl = redirectUrl;
            response.Message = message;

            return new JsonResult() { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        public bool IsValidEmailAddress(string s)
        {
            if (string.IsNullOrEmpty(s))
                return false;

            Regex re = new Regex(@"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (re.IsMatch(s))
                return true;
            else
                return false;

        }

        public bool IsNumber(string text)
        {
            try
            {
                Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
                return regex.IsMatch(text);
            }
            catch { return false; }
        }

        public bool IsNotCharter(string str)
        {
            try
            {
                Regex re = new Regex("^[-'a-zA-Z]*$");
                return re.IsMatch(str);
            }
            catch { return false; }
        }

        #region Images

        public string UploadImage(HttpPostedFileBase file)
        {
            string basePath = "~/Content/ImagesUpload/" + DateTime.Now.ToShortDateString();

            string[] fileNameArray = file.FileName.Split(new char[] { '.' });

            string ext = fileNameArray[fileNameArray.Length - 1];

            string fileNameTemp = "";

            int ytemp = fileNameArray.Length - 1;

            int i = 0;

            while (ytemp > 0)
            {
                fileNameTemp += _ihtml.RemoveSign4VietnameseString(fileNameArray[i]) + "-";
                i++;
                ytemp--;
            }

            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, ext, file.InputStream, fileNameTemp);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;
            return filePathStr;
        }

        [HttpPost]
        public ActionResult UploadImageStr(string qqfile)
        {
            string basePath = "~/Content/ImagesUpload/" + DateTime.Now.ToShortDateString();
            string[] fileNameArray = qqfile.Split(new char[] { '.' });
            if (fileNameArray.Length == 1)
            {
                return JsonError("lỗi");
            }

            string ext = fileNameArray[fileNameArray.Length - 1];

            string fileNameTemp = "";

            int ytemp = fileNameArray.Length - 1;

            int i = 0;

            while (ytemp > 0)
            {
                fileNameTemp += _ihtml.RemoveSign4VietnameseString(fileNameArray[i]) + "-";
                i++;
                ytemp--;
            }

            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, ext, Request.InputStream, fileNameTemp);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;
            return Json(new { success = true, filePath = Url.Content(basePath) + @"/" + fileName });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum,
                                      string CKEditor, string langCode)
        {
            string url = string.Empty; // url to return
            string message = string.Empty; // message to display (optional)

            // here logic to upload image
            // and get file path of the image

            // path of the image
            string path = UploadImage(upload);

            // will create http://localhost:1457/Content/Images/my_uploaded_image.jpg

            //url = Request.Url.GetLeftPart(UriPartial.Authority) + path;

            url = path;

            // passing message success/failure
            message = "Image was saved correctly";

            // since it is an ajax request it requires this string
            string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + message + "\");</script></body></html>";
            return Content(output);
        }


        

        #endregion

    }

    [Serializable]
    public class JsonResualt
    {
        [NonSerialized]
        public static readonly string OperationSuccess = "success";

        [NonSerialized]
        public static readonly string OperationFailure = "error";

        public string Status { get; set; }
        public string Message { get; set; }
        public string RedirectUrl { get; set; }
    }
}
